#include "authenticate.h"

uint32_t authenticate::PACKET_AUTHENTICATE_SIZE = 32;

authenticate::authenticate() : packet( 0, 0, Authenticate ), base( 0 ), exponent( 0 ), prime( 0 ), secret( 0 )
{}

void authenticate::init( MemoryPool<authenticate, 1000, 0, boost::function<authenticate *(void)> > *p, uint32_t _src, uint32_t _dst, uint64_t _base, uint64_t _exponent, uint64_t _prime )
{
	source.addr = _src;
	destination.addr = _dst;
	pool = p;
	base = _base;
	exponent = _exponent;
	prime = _prime;

	uint64_t t = base;
	for( int i = 0; i < exponent; i++ )
		t *= t;

	pub_key = t % prime;

	pool = p;
}


authenticate::~authenticate(void)
{}

void authenticate::print()
{
	packet::print();

	printf( "BASE: %llu\nEXPONENT: %llu\nPRIME: %llu\nPUB KEY: %llu\nSECRET: %llu\n", base, exponent, prime, pub_key, secret );
}

char *authenticate::serialize()
{
	curbuf = buffer_pool->create();
	char *header = packet::serialize();

	memcpy_s( curbuf, PACKET_AUTHENTICATE_SIZE, header, PACKET_HEADER_SIZE );

	buffer_pool->destroy( header );

	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x00 * sizeof( uint32_t )) = htonl( base & 0xFFFFFFFF00000000 >> 32 );
	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x01 * sizeof( uint32_t )) = htonl( base & 0x00000000FFFFFFFF );

	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x02 * sizeof( uint32_t )) = htonl( prime & 0xFFFFFFFF00000000 >> 32 );
	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x03 * sizeof( uint32_t )) = htonl( prime & 0x00000000FFFFFFFF );

	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x04 * sizeof( uint32_t )) = htonl( exponent & 0xFFFFFFFF00000000 >> 32 );
	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x05 * sizeof( uint32_t )) = htonl( exponent & 0x00000000FFFFFFFF );

	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x06 * sizeof( uint32_t )) = htonl( pub_key & 0xFFFFFFFF00000000 >> 32 );
	*(uint64_t *)(curbuf + PACKET_HEADER_SIZE + 1 + 0x07 * sizeof( uint32_t )) = htonl( pub_key & 0x00000000FFFFFFFF );

	return curbuf;
}
